package com.smyh.common;

import android.util.Log;

import com.smyh.cache.PreferenceCommon;
import com.smyh.cache.PreferenceSocketInfo;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Created by Administrator on 2016/7/13.
 */
public class MinaClientThread implements Runnable {
    public static ConnectFuture future = null;
    public static IoSession session = null;
    public static IoConnector connector = null;
    public static SocketAddress sa = null;
    public static boolean isCommplete = true;

    @Override
    public void run() {
        isCommplete = false;
        // TODO Auto-generated method stub
        int ip_1 = PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_1,192);
        int ip_2 = PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_2,168);
        int ip_3 = PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_3,1);
        int ip_4 = PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_4,1);

        String server_ip = ip_1 + "." + ip_2 + "." + ip_3 + "." + ip_4;
        int server_port = PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_PORT,9911);

//        Log.d("TEST","客户端链接开始...");
        connector = new NioSocketConnector();
        //设置链接超时时间
        connector.setConnectTimeoutMillis(30000);
        //添加过滤器
        //connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CharsetCodecFactory()));
//        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue())));
        connector.setHandler(new MinaHandler());
        sa = new InetSocketAddress(server_ip, server_port);

        try{
            future = connector.connect(sa);//创建链接
            future.awaitUninterruptibly();// 等待连接创建完成
            session = future.getSession();//获得session
        }catch (Exception e){
            isCommplete = true;
            Log.d("TEST","客户端链接异常...");
        }
        isCommplete = true;
    }


    public static void reConnect(){
        session.close(true);
        connector.dispose();
        new Thread(new MinaClientThread()).start();
    }

    public static void disConnect(){
        session.close(true);
        connector.dispose();
    }
}